package tools

import (
	"app-box/api_error"

	"github.com/golang-jwt/jwt/v4"
)

type TokenTool struct {
	jwtKey string
}

// 创建Token签发工具
// - jwtKey：token 加盐密钥
func NewTokenTool(jwtKey string) *TokenTool {
	var service = new(TokenTool)
	service.jwtKey = jwtKey
	return service
}

// 签发token
func (service *TokenTool) SignToken(token jwt.Claims) (string, api_error.ApiErrorType) {
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, token)
	tokenStr, err := tokenClaims.SignedString([]byte(service.jwtKey))
	if err != nil {
		return "", api_error.TokenCreateError(err)
	}
	return tokenStr, nil
}

// 解析Token
func (service *TokenTool) FormatToken(tokenStr string, tokenObject jwt.Claims) error {
	_, err := jwt.ParseWithClaims(tokenStr, tokenObject, func(token *jwt.Token) (i interface{}, err error) {
		return []byte(service.jwtKey), nil
	})
	if err != nil {
		return api_error.InvalidToken(err)

	}
	return nil
}
